<template>
  <view class="subscription__wrap">
    <transition name="fade">
      <view class="subscription">
        <view class="subscription__des">{{ des }}</view>
        <view class="subscription__buttons">
          <template v-if="rss">
            <button class="subscription__btn cancel" @click="cancelRss">
              取消订阅
            </button>
          </template>
          <template v-else>
            <button class="subscription__btn" @click="handleRss">
              订阅此书籍
            </button>
            <button class="subscription__btn cancel" @click="handleNoMoreShow">
              不再显示
            </button>
          </template>
        </view>
      </view>
    </transition>
    <Modal
      :show="showModal"
      @close="closeModal"
      title="温馨提示"
      content="检测到您未开启订阅消息通知权限，是否去设置？"
      confirm-type="openSetting"
      @cancel="closeModal"
    />
  </view>
</template>

<script>
import { mapGetters } from 'vuex';
import { get } from '@/utils/index';
import Modal from '@/components/Modal';
import { platformName } from '@/config';

export default {
  components: {
    Modal,
  },

  props: {
    rss: {
      type: Boolean,
      default: false,
    },

    bookid: {
      type: String,
      default: false,
    },
  },

  data() {
    return {
      show: true,
      showModal: false,
    };
  },

  computed: {
    ...mapGetters(['settings']),
    des() {
      if (!this.rss) {
        return '喜欢这本书的话，可以点击下方的订阅按钮来获取书籍的实时更新消息。';
      } else {
        return '你已经订阅本书籍，书籍有章节更新时，我们会及时通知你。你也可以点击下方按钮来取消订阅。';
      }
    },
  },

  methods: {
    handleRss() {
      // H5没有订阅消息，直接修改rss
      if (platformName === 'web') {
        this.requestRss(true);
        return;
      }
      const templateConfig = get(this.settings, 'template_ids', {});
      const templateIds = Object.values(templateConfig) || [];
      wx.requestSubscribeMessage({
        tmplIds: templateIds,
        success: (res) => {
          this.requestRss(true);
        },
        fail: (err) => {
          // 用户关闭了主开关，无法进行订阅
          if (err.errCode === '20004') {
            this.showModal = true;
            return false;
          }
          uni.showToast({ title: '订阅书籍失败', icon: 'none' });
        },
      });
    },

    /**
     * 保存用户的订阅记录
     */
    requestRss(rss = false) {
      this.$http({
        method: 'POST',
        url: '/api/front/booklist/rss',
        data: {
          bookid: this.bookid,
          rss: rss ? 1 : 0,
        },
        skipToast: false,
        needAuth: true,
        errorText: '订阅书籍失败',
      }).then((res) => {
        if (res.ok) {
          const rss = !this.rss;
          if (rss) {
            this.$store.commit('showSuccessTips', '订阅书籍成功');
          } else {
            uni.showToast({ title: '取消订阅成功', icon: 'none' });
          }
          this.$emit('update:rss', rss);
        }
      });
    },

    /**
     * 取消订阅
     */
    cancelRss() {
      this.requestRss(false);
    },

    /**
     * 点击不再显示
     */
    handleNoMoreShow() {
      const noMoreShowSubscriptBooks =
        uni.getStorageSync('noMoreShowSubscriptBooks') || [];
      if (noMoreShowSubscriptBooks.indexOf(this.bookid) < 0) {
        noMoreShowSubscriptBooks.push(this.bookid);
        uni.setStorageSync(
          'noMoreShowSubscriptBooks',
          noMoreShowSubscriptBooks
        );
      }
      this.$emit('close');
    },

    /**
     * 关闭弹窗提醒
     */
    closeModal() {
      this.showModal = false;
    },
  },
};
</script>

<style lang="scss">
.subscription {
  text-align: center;
  background: #fff;

  &__des {
    text-align: left;
    padding: 0 40rpx;
    font-size: 26rpx;
    color: #666;
  }

  &__btn {
    display: inline-block;
    width: auto;
    box-sizing: border-box;
    border: 1rpx solid #1aad19;
    background: none;
    margin-top: 40rpx;
    margin-bottom: 30rpx;
    color: #1aad19;
    font-size: 26rpx;
    box-sizing: content-box;
    padding: 0 30rpx;
    height: 64rpx;
    line-height: 65rpx;

    &:first-child {
      margin-right: 30rpx;
    }

    &:active {
      background: #479b25;
      color: #fff;
    }

    &.cancel {
      color: #666;
      border: 1rpx solid #666;

      &:active {
        background: #f8f8f8;
        color: rgba(0, 0, 0, 0.6);
      }
    }
  }
}
</style>
